package com.work.work.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.work.work.common.R;
import com.work.work.entity.Role;
import com.work.work.service.RoleService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Tag(name = "角色管理")
@RestController
@RequestMapping("/role")
public class RoleController {
    @Autowired
    private RoleService roleService;

    @Operation(summary = "创建角色")
    @PostMapping("/create")
    public R<Role> createRole(@RequestBody Role role) {
        if (role.getRolename() == null || role.getRolename().trim().isEmpty()) {
            return R.fail("角色名称不能为空");
        }
        return roleService.createRole(role) ? R.ok(role, "项目创建成功") : R.fail("创建角色失败");
    }

    @Operation(summary = "更新角色信息")
    @PutMapping("/{id}")
    public R<Boolean> updateRole(@PathVariable Integer id, @RequestBody Role role) {
        role.setId(id);
        return roleService.updateRole(role) ? R.ok(true, "项目创建成功") : R.fail("更新角色失败");
    }

    @Operation(summary = "删除角色")
    @DeleteMapping("/{id}")
    public R<Boolean> deleteRole(@PathVariable Integer id) {
        return roleService.removeById(id) ? R.ok(true, "项目创建成功") : R.fail("删除角色失败");
    }

    @Operation(summary = "获取角色详情")
    @GetMapping("/{id}")
    public R<Role> getRoleById(@PathVariable Integer id) {
        Role role = roleService.getById(id);
        return role != null ? R.ok(role, "项目创建成功") : R.fail("角色不存在");
    }

    @Operation(summary = "分页获取角色列表")
    @GetMapping("/page")
    public R<Page<Role>> getRoleList(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size) {
        return R.ok(roleService.getRoleList(current, size), "项目创建成功");
    }

    @Operation(summary = "获取所有角色")
    @GetMapping("/all")
    public R<List<Role>> getAllRoles() {
        return R.ok(roleService.getAllRoles(), "项目创建成功");
    }

    @Operation(summary = "搜索角色")
    @GetMapping("/search")
    public R<List<Role>> searchRoles(@RequestParam String keyword) {
        return R.ok(roleService.searchRoles(keyword), "项目创建成功");
    }
}